package com.example.service;


import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.Persistence;

import com.example.entities.User;

public class UserHandler {
	
	public void create(User user)
	{
		EntityManager em = EMFService.get().createEntityManager();
		em.getTransaction().begin();
		em.persist(user);
		
		em.getTransaction().commit();
		em.close();
		
	}
	
	public List<User> getAllUsers()
	
	{
		EntityManager em = EMFService.get().createEntityManager();
		em.getTransaction().begin();
		
		Query query = em.createQuery("SELECT p FROM User p");
		List<User> users = query.getResultList();
		
		em.getTransaction().commit();
		em.close();
		
		return users;
	}
	
	public int deleteByUsername(String userName)
	{
		EntityManager em = EMFService.get().createEntityManager();
		em.getTransaction().begin();
		
		Query q = em.createQuery("DELETE FROM User u WHERE u.userName = :u");
		q.setParameter("u", userName );
		int deleted = q.executeUpdate();
		
		em.getTransaction().commit();
		em.close();
		
		return deleted;

	}

}
